<template>
    <div>
     <!--面包屑导航区域-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
    <!--卡片视图区域-->
      <el-card class="box-card">
      <!--搜索区域-->
          <el-row :gutter="18">
            <el-col :span="8">
              <el-input placeholder="请输入内容" class="input-with-select" v-model="queryparams.query"  clearable @clear="getUserList">
                <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
              </el-input>
            </el-col>
            <el-col :span="4">
              <el-button type="primary"  @click="dialogVisible = true">添加用户</el-button>
            </el-col>
          </el-row>
        <!--用户列表区域-->
        <el-table
          :data="userList"
          border
          style="width: 100%" :stripe="true">
          <el-table-column   type="index"></el-table-column>
          <el-table-column  prop="username"  label="姓名"   width="180"></el-table-column>
          <el-table-column  prop="role_name" label="用户角色"></el-table-column>
          <el-table-column  prop="mobile"    label="电话"></el-table-column>
          <el-table-column  prop="email"     label="电子邮箱"></el-table-column>
          <el-table-column  label="状态" prop="mg_state">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.mg_state" @change="chgUserStatus(scope.row)" ></el-switch>
            </template>
          </el-table-column>
          <el-table-column  label="操作">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit"   @click="handleEdit(scope.row.id)"></el-button>
              <el-button type="danger" icon="el-icon-delete"   @click="handleDel(scope.row.id)"></el-button>
              <el-button type="primary" icon="el-icon-s-tools"   @click="handleConfig(scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页区域-->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryparams.pagenum"
          :page-sizes="[1, 2, 5, 7]"
          :page-size="queryparams.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-card>
      <!--用户对话框 添加用户-->
      <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="handleClose">
        <!--内容区域-->
        <el-form ref="addformref"  label-width="80px" :model="userfrmInfo" :rules="rules">
          <el-form-item label="用户名" prop="username">
            <el-input  v-model="userfrmInfo.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password" >
            <el-input  v-model="userfrmInfo.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input  v-model="userfrmInfo.email"></el-input>
          </el-form-item>
          <el-form-item label="手机 " prop="mobile">
            <el-input  v-model="userfrmInfo.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!--底部区域-->
        <span slot="footer" class="dialog-footer">
             <el-button @click="dialogVisible = false">取 消</el-button>
             <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!--编辑对话框代码-->
      <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
        <el-form ref="editformref"  label-width="80px" :model="editForm" :rules="rules">
          <el-form-item label="用户名"  >
            <el-input  v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input  v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机 " prop="mobile">
            <el-input  v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo">确 定</el-button>
        </span>
      </el-dialog>
      <!--角色配置对话框-->
      <el-dialog title="角色配置" :visible.sync="setRoleDialogVisible" width="50%"   @close="setRoleDialogClose">
        <p>当前的用户: {{userInfo.username}}</p>
        <p>当前的角色: {{userInfo.role_name}}</p>
        <p>分配新角色：
          <el-select v-model="selRoleId" clearable placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setRoleBtn">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
  export default {
    name: 'Users',
    data:function(){
      //<!--验证邮箱的规则-->
      var checkEmail=(rule,value,callback)=>{
        var regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
        if(regEmail.test(value)){
          return callback();
        }else{
          callback(new Error("请输入合法的邮箱!"));
        }
        }
        //验证手机号的规则
      var checkMobile=(rule,value,callback)=>{
        var regMobile =/^0{0,1}(13[0-9]|15[7-9]|153|156|18[7-9])[0-9]{8}$/;
        if(regMobile.test(value)){
          return callback();
        }else{
          callback(new Error("请输入合法的手机号!"));
        }
      }
      return {
        userList:{},
        total: 0,
        //获取用户列表的参数
        queryparams:{
          query:'',
          pagenum: 1,
          pagesize: 2
        },
        //对话框是否显示
        dialogVisible : false,
        userfrmInfo:{
          username:'',
          password:'',
          email:'',
          mobile:''
        },
        rules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 5, max: 12, message: '长度在 5 到 12 个字符', trigger: 'blur' }
          ],
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { validator: checkEmail, trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { validator: checkMobile , trigger:'blur'}
          ]
        },
        //控制编辑会话框是否显示
        editDialogVisible:false,
        //存储用户编辑的表单数据
        editForm:{},
        setRoleDialogVisible:false,
        userInfo:{},
        roleList:[],
        selRoleId:''
      }
    },
    created () {
      this.getUserList()
    },
    methods:{
      async getUserList(){
        let data=await this.$axios.get("users",{params:this.queryparams});
        let res=data.data;
        if(res.meta.status!='200') return this.$message.error("获取用户列表失败！");
        this.userList=res.data.users;
        this.total=res.data.total;
        console.log("res=",this.userList);
      },
   //编辑用户对话框
      async handleEdit(arg1){
       var data = await this.$axios.get('users/'+arg1);
       var res=data.data;
       if(res.meta.status!=200){
         return this.$message.err("获取用户信息失败!");
       }
        this.editForm=res.data;
        this.editDialogVisible=true;
      },
      //删除按键处理
      handleDel(id){
        this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          //处理删除
         var data=await this.$axios.delete('users/'+id);
         var res=data.data;
         if(res.meta.status!=200){return this.$message.error("用户删除失败!")}
         //重新获取数据
          this.getUserList();
          //提示删除成功
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //修改用户角色弹出窗口
      async handleConfig(userInfo){
        this.userInfo=userInfo;
        this.setRoleDialogVisible=true;
        //获取所有权限列表
       var data= await this.$axios.get('roles');
       var res=data.data;
       if(res.meta.status!=200){return this.$message.error("获取权限失败!")}
       this.roleList=res.data;
        console.log(this.roleList)
      },
      handleSizeChange(newsize){
       this.queryparams.pagesize=newsize;
       this.getUserList();
      },
      handleCurrentChange(pagenum){
        this.queryparams.pagenum=pagenum;
        this.getUserList();
      },
      async chgUserStatus(row){
      let result= await this.$axios.put(`users/${row.id}/state/${row.mg_state}`);
       if (result.data.meta.status!='200'){
         row.mg_state=!row.mg_state;
         return this.$message.error('状态更改失败!');
       }
       this.$message.success('状态更新成功!');
      },
     /* dialog关闭时,dialog对话框字段重置*/
      handleClose(){
        this.$refs.addformref.resetFields();
      },
     /* 点击确定按键,添加新用户*/
      addUser(){
        this.$refs.addformref.validate(async (valid)=>{
          if(!valid)  return;
          //发起网络请求
          var data=await this.$axios.post('users',this.userfrmInfo);
          var res=data.data;
          if(res.meta.status!=201){this.$message.error("用户添加失败!");}
          else{
            this.$message.success("用户添加成功!");
            //隐藏添加用户窗口
            this.dialogVisible=false;
            //更新列表
            this.getUserList();
          }
        });
      },
      //监听修改对话框的关闭事件
      editDialogClose(){
        this.$refs.editformref.resetFields();
      },
      //监听确定按键
      editUserInfo(){
        this.$refs.editformref.validate(async (valid)=>{
          if(!valid) return;
          //发起用户信息的数据请求
          var data=await  this.$axios.put("users/"+this.editForm.id,{
            email:this.editForm.email,mobile:this.editForm.mobile});
          var res=data.data;
          if(res.meta.status!=200){return this.$message.error("获取用户信息失败!")}
          //关闭对话框
          this.editDialogVisible=false;
          //刷新数据列表
          this.getUserList();
          //提示修改成功
          this.$message.success("更新用户成功!");
        });
      },
      //角色配置窗口弹出中的保存按键事件
      async setRoleBtn () {
        if (!this.selRoleId) {
          return this.$message.error('请选中要分配的角色!')
        }
        var data = await this.$axios.put('users/' + this.userInfo.id + '/role',{rid:this.selRoleId});
        var res = data.data;
        console.log("setRoleres=",res);
        if(res.meta.status!=200){
         return  this.$message.error("分配用户角色失败!");
        }
        this.$message.success("分配用户角色成功!");
        this.getUserList();
        this.setRoleDialogVisible=false;

      },
      //角色配置窗口关闭后清空
      setRoleDialogClose(){
        this.selRoleId='';
      }


    }
  }
</script>

<style scoped>
.el-table{
  margin-top: 15px;
  font-size: 10px;
}
  .el-button{
    margin-left: 10px;
  }
</style>
